<?php
if(!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Code Igniter
*
* An open source application development framework for PHP 4.3.2 or newer
*
* @package		CodeIgniter
* @author		Rick Ellis
* @copyright	Copyright (c) 2006, pMachine, Inc.
* @license		http://www.codeignitor.com/user_guide/license.html
* @link			http://www.codeigniter.com
* @since        Version 1.0
* @filesource
*/

// ------------------------------------------------------------------------

/**
* Code Igniter Asset Helpers
*
* @package		CodeIgniter
* @subpackage	Helpers
* @category		Helpers
* @author       Philip Sturgeon < phil.sturgeon@styledna.net >
*/

// ------------------------------------------------------------------------


/**
* General Asset Helper
*
* Helps generate links to asset files of any sort. Asset type should be the
* name of the folder they are stored in.
*
* @access		public
* @param		string    the name of the file or asset
* @param		string    the asset type (name of folder)
* @param		string    optional, module name
* @return		string    full url to asset
*/
if( ! function_exists('delete_directory'))
{
	function delete_directory($dirname)
	{
		if(is_dir($dirname))	      $dir_handle = opendir($dirname);
		if(!$dir_handle)	      return false;
		while($file = readdir($dir_handle)){
			if($file != "." && $file != ".."){
				if(!is_dir($dirname."/".$file))	            unlink($dirname."/".$file);
				else	            delete_directory($dirname.'/'.$file);
			}
		}
		closedir($dir_handle);
		rmdir($dirname);
		return true;
	}
}

if( ! function_exists('copy_directory'))
{
	function copy_directory( $source, $destination ) {
		if ( is_dir( $source ) ) {
			@mkdir( $destination );
			$directory = dir( $source );
			while ( FALSE !== ( $readdirectory = $directory->read() ) ) {
				if ( $readdirectory == '.' || $readdirectory == '..' ) {
					continue;
				}
				$PathDir = $source . '/' . $readdirectory; 
				if ( is_dir( $PathDir ) ) {
					copy_directory( $PathDir, $destination . '/' . $readdirectory );
					continue;
				}
				copy( $PathDir, $destination . '/' . $readdirectory );
			}
	 
			$directory->close();
		}else {
			copy( $source, $destination );
		}
	}
}

if( ! function_exists('CI'))
{
	function CI($function,$param = NULL)
	{
		$CI =& get_instance();
		return eval('$CI->'.$function.'('.$param.');');
	}
}

if( ! function_exists('generate_th_orderby'))
{
	function generate_th_orderby($data = array(),$additional_url = NULL)
	{
		$CI         =& get_instance();
		$returnData = '';
		foreach($data as $key => $value):
		$templates = (!empty($value['templates']) ? $value['templates']:'');
		$width = (!empty($value['width']) ? 'width:'.$value['width'].'px':'');
		switch($templates):
		case 'checkbox':
		$returnData .= '<th style="'.$width.'" class="manage-column check-column clean-column" scope="col"><span>'.$value['name'].'</span></th>';
		break;
		case 'sort':
		$returnData .= '<th style="'.$width.'" class="manage-column small-column clean-column" scope="col"><span>'.$value['name'].'</span></th>';
		break;
		case 'tools':
		$returnData .= '<th style="'.$width.'" class="manage-column tools-column clean-column" scope="col"><span>'.$value['name'].'</span></th>';
		break;
		default:
		if(!empty($value['orderby'])):
		$the_uri_query = query_string(array('orderby','sort'));
		if(!empty($the_uri_query)) $the_uri_query = "&".$the_uri_query;
		$returnData .= '<th style="'.$width.'" class="manage-column '.($CI->input->get('orderby') == $value['orderby'] ? 'sorted':'sortable').' '.($CI->input->get('orderby') == $value['orderby'] && $CI->input->get('sort') == 'desc' ? 'asc':'desc').'" scope="col"><a href="'.get_url(3).$additional_url.'?orderby='.$value['orderby'].'&amp;sort='.($CI->input->get('orderby') == $value['orderby'] && $CI->input->get('sort') == 'desc' ? 'asc':'desc').$the_uri_query.'" title="'.$value['name'].'"><span>'.$value['name'].'</span><span class="sorting-indicator">&nbsp;</span></a></th>';
		else:
		$returnData .= '<th style="'.$width.'" class="manage-column  clean-column" scope="col"><span>'.$value['name'].'</span></th>';
		endif;
		endswitch;
		endforeach;
		return $returnData;
	}
}

if( ! function_exists('query_string'))
{
	function query_string($remove = array(),$repalcewith = "")
	{
		$CI =& get_instance();
		if(!empty($remove)):
			$regex = array();
			$replace = array();
			foreach($remove as $value):
			$regex[] = '/'.$value.'=(.+?(\&)|)/';
			$replace[] = $repalcewith;
			endforeach;
			return rtrim(preg_replace($regex,$replace,$CI->input->server('QUERY_STRING').'&'),'&');
		else:
			return rtrim($CI->input->server('QUERY_STRING'),'&');
		endif;
	}
}

if( ! function_exists('get_url'))
{
	function get_url($segment = NULL)
	{
		$CI =& get_instance();
		if(!empty($segment) && is_numeric($segment)):
		$segments = array();
		for($i = 1;$i <= $segment;$i++):
		$segments[] = $CI->uri->segment($i);
		endfor;
		return site_url(implode('/',$segments));
		else:
		return current_url();
		endif;
	}
}

if( ! function_exists('seo_url'))
{
	function seo_url($str,$join='-')
	{
		//$permitted_uri_chars = 'เ-๙a-z0-9%_\-\+\=';
		$CI =& get_instance();
		$permitted_uri_chars = $CI->config->item('permitted_uri_chars');
		//clean string first
		$str = strtolower(preg_replace('/(\‘|\’|\'|\“|\”)/','',$str));
		$str = strtolower(preg_replace('/%/','เปอร์เซ็นต์',$str));
		$str = rtrim(preg_replace('/[^'.$permitted_uri_chars.']/',$join,$str),$join);
		$str = preg_replace('/('.$join.')+/',$join,$str); //ex. -- to -
		return ltrim($str,$join);
	}
}

if( ! function_exists('convertDatetime'))
{
	function convertDatetime($str)
	{
		return preg_replace('/(\d{2})\/(\d{2})\/(\d{4})/','$3-$2-$1',$str);
	}
}

if( ! function_exists('convertDatetimeToString'))
{
	function convertDatetimeToString($datetime)
	{
		return preg_replace('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/','$3/$2/$1 $4:$5',$datetime);
	}
}

if( ! function_exists('convertDatetimeToThai'))
{
	function convertDatetimeToThai($datetime)
	{
		return preg_replace_callback('/(\d{4})-(\d{2})-(\d{2})/',create_function('$matches','
			$month_thai_arr = array("ม.ค.","ก.พ.","มี.ค.","เม.ย.","พ.ค.","มิ.ย.","ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค.",);
			$year_thai = 543;
		 	return $matches[3]." ".$month_thai_arr[intval($matches[2])-1]." ".(intval($matches[1])+$year_thai);
		'),$datetime);
	}
}

if( ! function_exists('sendEmail'))
{
	function sendEmail($data,$mailtype = 'text')
	{
		$CI =& get_instance();
		//Load Library
		$CI->load->library('email');

		$config['protocol'] = $CI->config->item('protocol');
		$config['smtp_host'] = $CI->config->item('smtp_host');
		$config['smtp_user'] = $CI->config->item('smtp_user');
		$config['smtp_pass'] = $CI->config->item('smtp_pass');
		$config['smtp_port'] = $CI->config->item('smtp_port');
		$config['mailtype'] = $mailtype;
		$config['charset'] = $CI->config->item('charset');
		$config['wordwrap'] = $CI->config->item('wordwrap');

		$CI->email->initialize($config);
		$CI->email->from(''.$data->sender_email.'', ''.$data->sender_name.'');
		$CI->email->to(''.$data->receiver_email.'');
		$CI->email->subject(''.$data->receiver_subject.'');
		$CI->email->message(''.$data->receiver_message.'');

		// Attach the uploaded file if it is set
		if(!empty($data->attach_file)):
		foreach($data->attach_file as $key => $value):
		$CI->email->attach($key,$value);
		endforeach;
		endif;

		//Send mail
		$CI->email->send();	
	}
}

if( ! function_exists('imageResize'))
{
	function imageResize($data = array(),$file_name = NULL)
	{
		$CI       =& get_instance();
		//Load Library
		$CI->load->library('image_lib');

		//Make folder
		$new_path = $data['new_path'].'original/';
		@mkdir($new_path);
		//Get New Name
		$path_info= pathinfo($data['source_image']);
		//Check file_name
		if(empty($file_name)):
			$file_name= md5($data['id'].rand());
			$new_image= $new_path.$file_name.'.'.$path_info['extension'];
			while(file_exists(realpath($new_image))):
				$file_name = md5($data['id'].rand());
				$new_image = $new_path.$file_name.'.'.$path_info['extension'];
			endwhile;
		else:
			$new_image = $new_path.$file_name.'.'.$path_info['extension'];
		endif;
		@copy($data['source_image'],$new_image); //Put File to original
		
		//Watermark
		@mkdir($data['new_path'].'watermark/');
		$source_file = $data['new_path'].'watermark/'.$file_name.'.'.$path_info['extension'];
		@copy($new_image,$source_file); //Put File to Watermark	
		//Watermark
		if(!empty($data['watermark'])):
			preg_match('/watermark\/(.+?\.png)/',$data['watermark'],$matches);
			$watermark_ratio_file = $data['new_path'].'watermark/'.$matches[1];	
			if(!isset($data['watermark_original']) || $data['watermark_original'] == false): //resize watermark		
				$config   = array(
					'source_image'  => $source_file
				);
				$CI->image_lib->initialize($config);
				if($CI->image_lib->orig_width > $CI->image_lib->orig_height){
					$watermark_width = ceil($CI->image_lib->orig_width * 0.14);	
				} else {
					$watermark_width = ceil($CI->image_lib->orig_height * 0.14);
				}
				$config   = array(
					'image_library' => 'gd2',
					'source_image'  => $data['watermark'],
					'new_image'     => $watermark_ratio_file,
					'width'         => $watermark_width,
					'master_dim'        => 'width',
					'create_thumb'  => FALSE,
					'maintain_ratio'=> TRUE
				);
				$CI->image_lib->initialize($config);
				$CI->image_lib->resize();
				//Clear Image
				$CI->image_lib->clear();		
			else:
				@copy($data['watermark'],$watermark_ratio_file); //Put File to Watermark Folder
			endif;
			//Put watermark
			$config = array(
				'source_image' => $source_file,
				'wm_type' => 'overlay',
				'quality' => '100%',
				'wm_vrt_alignment' => (isset($data['watermark_horizontal']) && !empty($data['watermark_horizontal']) ? $data['watermark_horizontal']:'bottom'),
				'wm_hor_alignment' => (isset($data['watermark_vertical']) && !empty($data['watermark_vertical']) ? $data['watermark_vertical']:'right'),
				'wm_overlay_path' => $watermark_ratio_file,
				'wm_opacity' => '100'
			);
			$CI->image_lib->initialize($config);			
			
			$CI->image_lib->watermark();
			//Clear Image
			$CI->image_lib->clear();
		endif;

		//Resize && Crop
		if(!empty($data['dimension'])) foreach($data['dimension'] as $size):
			//Make folder
			$new_path = $data['new_path'].$size['width'].'x'.$size['height'].'/';
			@mkdir($new_path);
			$new_image= $new_path.$file_name.'.'.$path_info['extension'];

			$config   = array(
				'image_library' => 'gd2',
				'source_image'  => $data['source_image'],
				'new_image'     => $new_image,
				'width'         => $size['width'],
				'height'        => $size['height'],
				'create_thumb'  => FALSE,
				'maintain_ratio'=> TRUE
			);
			$CI->image_lib->initialize($config);

			//Dimension Calculate && resize && crop
			if(($CI->image_lib->orig_width / $size['width']) < ($CI->image_lib->orig_height / $size['height'])): //rectangular
				$config['master_dim'] = 'width';
			elseif(($CI->image_lib->orig_width / $size['width']) > ($CI->image_lib->orig_height / $size['height'])): //rectangular
				$config['master_dim'] = 'height';
			else: //square
				//Nothing
			endif;
			$CI->image_lib->initialize($config);
			$CI->image_lib->resize();
			//Crop Setting
			$x_axis = ($CI->image_lib->width == $size['width'] ? 0:floor(($CI->image_lib->width - $size['width']) / 2));
			$y_axis = ($CI->image_lib->height == $size['height'] ? 0:floor(($CI->image_lib->height - $size['height']) / 2));
			//Crop Actual size
			$CI->image_lib->clear();
			$config = array(
				'image_library' => 'gd2',
				'source_image'  => $new_image,
				'new_image'     => $new_image,
				'width'         => $size['width'],
				'height'        => $size['height'],
				'create_thumb'  => FALSE,
				'x_axis'        => ''.$x_axis.'',
				'y_axis'        => ''.$y_axis.'',
				'maintain_ratio'=> FALSE
			);
			$CI->image_lib->initialize($config);
			$CI->image_lib->crop();

			//Clear Image
			$CI->image_lib->clear();
		endforeach;

		//return some value
		$data = array(
			'file_name'=> $file_name,
			'file_ext' => $path_info['extension']
		);
		return (object)$data;
	}
}

if( ! function_exists('exec_image'))
{
	function exec_image($data = array())
	{
		$CI       =& get_instance();
		$upload_path = $CI->config->item('path_asset_url').'assets/uploads/';
		$folder = $data['folder'].'/images/';
		$dimension = $data['dimension'].'/';
		list($width,$height) = explode('x',$data['dimension']);
		$file_name = $data['file_name'];
		$title = preg_replace("/\"/","",$data['title']);
		$alt = preg_replace("/\"/","",$data['alt']);
		$attr = array(
			'width' => $width,
			'height' => $height,
			'title' => ''.$title.'',
			'alt' => ''.$alt.''
		);
		if(!empty($data['id'])) $attr['id'] = $data['id'];
		if(file_exists($upload_path.$folder.$dimension.$file_name) && !($file_name=='.' || $file_name=='')):
			return image_asset('../uploads/'.$folder.$dimension.$file_name,'',$attr);
		elseif(file_exists($upload_path.$folder.'original/'.$file_name) && !($file_name=='.' || $file_name=='')):
			$data = imageResize(array(
				'source_image' => $upload_path.$folder.'original/'.$file_name,
				'new_path' => $upload_path.$folder,
				'dimension' => array(
					array(
						'width' => $width,
						'height' => $height
					)
				)
			),preg_replace("/\.\w{3}/","",$file_name));
			return image_asset('../uploads/'.$folder.$dimension.$file_name,'',$attr);
			return false;
		else:
			return false;
		endif;				
	}
}

// Pretty print some JSON
if( ! function_exists('jsonpp'))
{
	/**
	 * jsonpp - Pretty print JSON data
	 *
	 * In versions of PHP < 5.4.x, the json_encode() function does not yet provide a
	 * pretty-print option. In lieu of forgoing the feature, an additional call can
	 * be made to this function, passing in JSON text, and (optionally) a string to
	 * be used for indentation.
	 *
	 * @param string $json  The JSON data, pre-encoded
	 * @param string $istr  The indentation string
	 *
	 * @return string
	 */
	function jsonpp($json, $istr='  ')
	{
	    $result = '';
	    for($p=$q=$i=0; isset($json[$p]); $p++)
	    {
	        $json[$p] == '"' && ($p>0?$json[$p-1]:'') != '\\' && $q=!$q;
	        if(strchr('}]', $json[$p]) && !$q && $i--)
	        {
	            strchr('{[', $json[$p-1]) || $result .= "\n".str_repeat($istr, $i);
	        }
	        $result .= $json[$p];
	        if(strchr(',{[', $json[$p]) && !$q)
	        {
	            $i += strchr('{[', $json[$p])===FALSE?0:1;
	            strchr('}]', $json[$p+1]) || $result .= "\n".str_repeat($istr, $i);
	        }
	    }
	    return $result;
	}
} 
?>